/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaCidade.java
 *
 * Created on 17/07/2011, 10:23:13
 */
package manager.principal.fonte;

import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.TableRowSorter;
import manager.auxiliares.Configurations;
import manager.auxiliares.Format;
import manager.auxiliares.Icons;
import manager.auxiliares.MensagemExcessao;
import manager.auxiliares.WindowsFunctions;
import manager.helpers.table.TableModel;
import manager.helpers.table.TableRender;
import manager.helpers.table.TableRowComparator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.principal.dao.CidadeDao;
import manager.interfaces.InterfaceRegister;
import manager.interfaces.InterfaceTable;
import manager.principal.dao.EstadoDao;

/**
 *
 * @author Thiago
 */
public class JanelaCidade extends javax.swing.JFrame {

    private TableModel tableModel;
    private TableRender tableRender;
    private TableRowSorter tableRowSorter;
    private int idCity;

    /** Creates new form JanelaCidade */
    public JanelaCidade() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            initComponents();
            configurarJanela();
            this.setIconImage(JanelaLogin.icon);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private LinkedList<String> validarCampos() {
         LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField1).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField1).getjLabel().getText());
        }
        return fieldList;
    }

    private void configurarTabela() {
        tableRender = new TableRender();
        tableModel = new TableModel(this.getColumnNameSearch(), tableRender, new InterfaceTable() {

            public void tableAction(int id, int columnIndex,int rowIndex) {
                if (columnIndex < 0) {
                    setEntidade(id);
                }
            }

            public boolean isEditableColumn(int columnIndex) {
                if (columnIndex == 0) {
                    return true;
                }
                return false;
            }
        });
        jTable1.setModel(tableModel);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(30);
        jTable1.getColumnModel().getColumn(0).setMinWidth(30);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        tableRowSorter = this.getTableSorter();
        jTable1.setRowSelectionAllowed(false);
    }

    private void setEntidade(int idCity) {
        this.idCity = idCity;
        jButton1.setToolTipText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        CidadeDao cidadeDao = new CidadeDao();
        cidadeDao.buscar(idCity);
        jTextField1.setText(cidadeDao.getNome());
        jComboBox2.setSelectedItem(EstadoDao.getNomeEstadoPorId(cidadeDao.getIdEstado()));
        verificarCamposObrigatorios();
        jButton2.setEnabled(true);
        jTextField1.requestFocus();
    }
    
    private void cancelEdit(){
        idCity = 0;
        jButton1.setToolTipText("Adicionar");
        jButton1.setIcon(new Icons().getAdd());
        jButton2.setEnabled(false);
        jTextField1.setText("");
        verificarCamposObrigatorios();
        jTextField1.requestFocus();
    }

    private void addCity() {
        if (CidadeDao.getIdCidadePorNome(jTextField1.getText()) == 0) {
            try {
                CidadeDao cityDao = new CidadeDao();
                cityDao.setNome(jTextField1.getText());
                cityDao.setIdEstado(EstadoDao.getIdEstadoPorNome(jComboBox2.getSelectedItem().toString()));
                cityDao.inserir();

                JOptionPane.showMessageDialog(null, "Cidade cadastrada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (Exception e) {
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            }
        } else {
            JOptionPane.showMessageDialog(null, "Esta cidade já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }

    private void editCity() {
        CidadeDao cityDao = new CidadeDao();
        cityDao.buscar(idCity);
        if (CidadeDao.getIdCidadePorNome(jTextField1.getText()) == 0 || cityDao.getNome().equals(jTextField1.getText())) {
            try {
                cityDao.setNome(jTextField1.getText());
                cityDao.setIdEstado(EstadoDao.getIdEstadoPorNome(jComboBox2.getSelectedItem().toString()));
                cityDao.atualizar();

                JOptionPane.showMessageDialog(null, "Cidade editada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (Exception e) {
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            }
        } else {
            JOptionPane.showMessageDialog(null, "Esta cidade já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }

    private void buscarTabela() {
        tableModel.update(this.searchTable("Nome", ""));
        jTable1.setDefaultRenderer(Object.class, tableRender);
        tableRowSorter.setModel(tableModel);

        jTable1.setRowSorter(tableRowSorter);
    }

    private void verificarCamposObrigatorios() {
        ((TextFieldValidator) jTextField1).validarCampo();

    }

    /**
     * Inicializando as configurações da tela
     * @throws SQLException 
     */
    private void configurarJanela() {
        idCity = 0;
        verificarCamposObrigatorios();
        configurarTabela();
        buscarTabela();

        Format.formatarComboBoxUf(jComboBox2, "RN");
        
        jTextField1.requestFocus();
    }
    
     private LinkedList searchTable(String option, String search) {
        LinkedList result = new LinkedList();
        try {
            result = CidadeDao.searchTable();
        } catch (SQLException ex) {
            MensagemExcessao.mostrarMensagem(ex, "Buscando Cidades");
        }
        return result;
    }
     
    private LinkedList<String> getColumnNameSearch() {
        LinkedList<String> columnNames = new LinkedList<String>();
        columnNames.add("");
        columnNames.add("Cidades");
        return columnNames;
    }
    
    private TableRowSorter getTableSorter() {
        TableRowComparator tableRowComparator = new TableRowComparator();
        return tableRowComparator;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new TextFieldValidator(80, -1, true, true, "text", jLabel1);
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel41 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cidades");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setLayout(null);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel2.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Cidade");
        jPanel2.add(jLabel1);
        jLabel1.setBounds(10, 5, 120, 14);

        jTextField1.setNextFocusableComponent(jButton1);
        jPanel2.add(jTextField1);
        jTextField1.setBounds(10, 25, 235, 20);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setToolTipText("Adicionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);
        jButton1.setBounds(295, 10, 30, 30);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton2.setToolTipText("Cancelar");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(330, 10, 30, 30);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(jTable1);

        jPanel2.add(jScrollPane3);
        jScrollPane3.setBounds(10, 50, 350, 240);

        jLabel41.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel41.setText("UF");
        jPanel2.add(jLabel41);
        jLabel41.setBounds(250, 5, 14, 14);

        jPanel2.add(jComboBox2);
        jComboBox2.setBounds(250, 25, 40, 20);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(0, 0, 370, 300);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCampos();
        if (fieldValidadeList.size() == 0) {
            if (idCity == 0) {
                addCity();
            } else {
                editCity();
            }
        } else {
            JOptionPane.showMessageDialog(null,ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel1, jPanel2);
}//GEN-LAST:event_formComponentResized

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        cancelEdit();
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel41;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
